package com.lch.webdemo.wxhandler;

import com.lch.webdemo.wxservice.WeixinService;
import com.lch.webdemo.wxservice.builder.TextBuilder;

import org.springframework.stereotype.Component;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 关注事件
 *
 * @author liuchenhui
 */
@Component
@Slf4j
public class SubscribeHandler extends AbstractHandler {


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {

        log.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        WeixinService weixinService = (WeixinService) wxMpService;

        try {
            // 获取微信用户基本信息
            WxMpUser user = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
            if (user != null) {
                // TODO: liuchenhui 记录
                log.info("用户信息user={}", user);
            }
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return new TextBuilder().build("感谢关注", wxMessage, weixinService);
    }
}
